<template>
  <div>
    <div class="search-term">
      <el-form :inline="true" :model="searchInfo" class="demo-form-inline">
		  <el-form-item label="操作人员">
			<el-input placeholder="请输入" v-model="searchInfo.username" clearable @clear="getTableData"></el-input>
		  </el-form-item>
        <el-form-item label="请求方法">
          <!-- <el-input placeholder="搜索条件" v-model="searchInfo.method"></el-input> -->
		  <el-select v-model="searchInfo.method" placeholder="请选择" size="small" clearable filterable @clear="getTableData">
			  <el-option label="GET(查询)" value="GET"></el-option>
			  <el-option label="POST(查询)" value="POST"></el-option>
			  <el-option label="PUT(更新)" value="PUT"></el-option>
			  <el-option label="DELETE(删除)" value="DELETE"></el-option>
		  </el-select>
        </el-form-item>
        <el-form-item label="请求路径">
			<el-select v-model="searchInfo.path" placeholder="请输入路径" size="small" clearable filterable @clear="getTableData">
				<el-option :key="item" v-for="item in api_path_list" :label="item" :value="item"></el-option>
			</el-select>
          <!-- <el-input placeholder="搜索条件" v-model="searchInfo.path"></el-input> -->
        </el-form-item>
		<el-form-item label="操作描述">
			<el-select v-model="searchInfo.desc" placeholder="请输入描述" size="small" clearable filterable @clear="getTableData">
				<el-option :key="item" v-for="item in api_desc_list" :label="item" :value="item"></el-option>
			</el-select>
		</el-form-item>
        <el-form-item label="结果状态码">
          <el-input placeholder="请输入状态码" v-model="searchInfo.status" clearable @clear="getTableData"></el-input>
        </el-form-item>
		<el-form-item label="日期范围">
			 <el-date-picker
			      v-model="searchInfo.daterange"
			      type="daterange"
			      align="right"
			      unlink-panels
			      range-separator="至"
			      start-placeholder="开始日期"
			      end-placeholder="结束日期"
			      :picker-options="pickerOptions">
			    </el-date-picker>
		</el-form-item>
        <el-form-item>
			<el-button type="primary" icon="el-icon-search" @click="onSubmit" size="mini">搜索</el-button>
        </el-form-item>
		<el-form-item>
		  <el-button icon="el-icon-refresh" @click="resetQuery" size="mini">重置</el-button>
		</el-form-item>
      </el-form>
	  <el-row :gutter="10" style="margin-bottom: 8px;margin-top: 12px">
                 <el-col :span="1.5">
                     <el-button
                             type="danger"
                             icon="el-icon-delete"
                             size="mini"
                             :disabled="multiple"
                             @click="handleDelete"
                     >删除</el-button>
                 </el-col>
                 <el-col :span="1.5">
                     <el-button
                             type="danger"
                             icon="el-icon-delete"
                             size="mini"
                             @click="handleClean"
                     >清空</el-button>
                 </el-col>
                 <el-col :span="1.5">
                     <el-button
                             type="warning"
                             icon="el-icon-download"
                             size="mini"
                             :disabled="multiple"
                             @click="handleExportSelected"
                     >导出选中
                     </el-button>
                 </el-col>
                 <el-col :span="2">
                     <el-button
                             type="success"
                             icon="el-icon-download"
                             size="mini"
                             @click="handleExportAll"
                     >导出所有</el-button>
                 </el-col>
             </el-row>
		</div>
    <el-table
      :data="tableData"
	  :row-key="getRowKeys"
      @selection-change="handleSelectionChange"
	  :header-cell-style="table_header"
      border
      ref="multipleTable"
      stripe
      style="width: 100%"
      tooltip-effect="dark"
    >
      <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>
      <el-table-column label="操作人员" width="80" prop="username" align="center"></el-table-column>
      <el-table-column label="时间" width="160" align="center">
        <template slot-scope="scope">{{scope.row.CreatedAt|formatDate}}</template>
      </el-table-column>
	  <el-table-column label="描述" width="100" prop="desc" align="center"></el-table-column>
      <el-table-column label="状态码" prop="status" width="70" align="center">
        <template slot-scope="scope">
          <div>
            <el-tag type="success">{{ scope.row.status }}</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="主机" prop="ip" width="100" align="center"></el-table-column>
      <el-table-column label="耗时" prop="latency" width="100" align="center"></el-table-column>
      <el-table-column label="操作地点" prop="location" width="90" align="center"></el-table-column>
      <el-table-column label="浏览器" prop="browser" width="90" align="center"></el-table-column>
      <el-table-column label="操作系统" prop="os" width="90" align="center"></el-table-column>
      <el-table-column label="平台" prop="platform" width="90" align="center"></el-table-column>
      <el-table-column label="请求方法" prop="method" width="80" align="center"></el-table-column>
      <el-table-column label="请求路径" prop="path" width="150" align="center"></el-table-column>
      <el-table-column label="参数" prop="path" width="80" align="center">
        <template slot-scope="scope">
          <div>
            <el-popover placement="top-start" trigger="hover" v-if="scope.row.body">
              <div class="popover-box">
                <pre>{{fmtBody(scope.row.body)}}</pre>
              </div>
              <i class="el-icon-view" slot="reference"></i>
            </el-popover>

            <span v-else>无</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="响应" prop="path" width="80" align="center" fixed="right">
        <template slot-scope="scope">
          <div>
            <el-popover placement="top-start" trigger="hover" v-if="scope.row.resp">
              <div class="popover-box">
                <pre>{{fmtBody(scope.row.resp)}}</pre>
              </div>
              <i class="el-icon-view" slot="reference"></i>
            </el-popover>
            <span v-else>无</span>
          </div>
        </template>
      </el-table-column>
      <!-- <el-table-column label="操作" align="center" fixed="right">
        <template slot-scope="scope">
          <el-popover placement="top" v-model="scope.row.visible" width="160">
            <p>确定要删除吗？</p>
            <div style="text-align: right; margin: 0">
              <el-button @click="scope.row.visible = false" size="mini" type="text">取消</el-button>
              <el-button @click="deleteSysOperationRecord(scope.row)" size="mini" type="primary">确定</el-button>
            </div>
            <el-button icon="el-icon-delete" size="mini" slot="reference" type="danger">删除</el-button>
          </el-popover>
        </template>
      </el-table-column> -->
    </el-table>
    <el-pagination
      :current-page="page"
      :page-size="pageSize"
      :page-sizes="[10, 30, 50, 100]"
      :style="{float:'right',padding:'20px'}"
      :total="total"
	  background
	  prev-text="上一页"
	  next-text="下一页"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
      layout="total, sizes, prev, pager, next, jumper"
    ></el-pagination>
  </div>
</template>

<script>
import {
  deleteSysOperationRecord,
  getSysOperationRecordList,
  getSysOperationRecordsByIds,
  deleteSysOperationRecordByIds,
  cleanSysOperationRecord
} from '@/api/sysOperationRecord' //  此处请自行替换地址
import {getApiPathAndDesc} from '@/api/api'
import { formatTimeToStr } from '@/utils/date'
import {formatJson} from "@/utils/index"
import infoList from '@/mixins/infoList'

export default {
  name: 'SysOperationRecord',
  mixins: [infoList],
  data() {
    return {
      listApi: getSysOperationRecordList,
      dialogFormVisible: false,
      visible: false,
	  multiple: true,
      type: '',
      deleteVisible: false,
      multipleSelection: [],
      formData: {
        ip: null,
        method: null,
        path: null,
        status: null,
        latency: null,
        agent: null,
        error_message: null,
        user_id: null
      },
	  api_path_list: [],
	  api_desc_list: [],
	  downloadLoading: false,
	  pickerOptions: {
		shortcuts: [{
		  text: '最近一周',
		  onClick(picker) {
			const end = new Date();
			const start = new Date();
			start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
			picker.$emit('pick', [start, end]);
		  }
		}, {
		  text: '最近一个月',
		  onClick(picker) {
			const end = new Date();
			const start = new Date();
			start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
			picker.$emit('pick', [start, end]);
		  }
		}, {
		  text: '最近三个月',
		  onClick(picker) {
			const end = new Date();
			const start = new Date();
			start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
			picker.$emit('pick', [start, end]);
		  }
		}]
	  },
    }
  },
  filters: {
    formatDate: function(time) {
      if (time != null && time != '') {
        var date = new Date(time)
        return formatTimeToStr(date, 'yyyy-MM-dd hh:mm:ss')
      } else {
        return ''
      }
    },
    formatBoolean: function(bool) {
      if (bool != null) {
        return bool ? '是' : '否'
      } else {
        return ''
      }
    }
  },
  methods: {
	table_header(row, column, rowIndex, columnIndex){
		  return 'background-color: #409EFF; color: white; font-size: 12px;'
	  },
	  getRowKeys(row){
		  return row.ID
	  },
    //条件搜索前端看此方法
    onSubmit() {
      this.page = 1
      this.pageSize = 10
      this.getTableData()
    },
    handleSelectionChange(val) {
	  if (val.length === 0){
			this.multipleSelection = [];
	  }else{
		    this.multipleSelection = val.map(item => item.ID);  
	  }
	  this.multiple = !val.length;
    },
	resetQuery(){
		this.searchInfo = {};
	},
    async handleDelete() {
	  var v1 = this;
      const ids = this.multipleSelection;
	  this.$confirm('是否确认删除日志编号为"' + ids + '"的数据项?', '警告', {
	                  confirmButtonText: '确定',
	                  cancelButtonText: '取消',
	                  type: 'warning'
		  }).then(async () => {		  
		  const res = await deleteSysOperationRecordByIds({ ids });
		  if (res.code === 0) {
			v1.$message({
			  type: 'success',
			  message: '删除成功'
			})
			v1.getTableData();
			v1.multipleSelection = [];
			this.multiple = true;
		  }else{
			  return v1.$message.error(res.msg);
		  }
		}).catch(function(){})
    },
    async deleteSysOperationRecord(row) {
      this.visible = false
      const res = await deleteSysOperationRecord({ ID: row.ID })
      if (res.code == 0) {
        this.$message({
          type: 'success',
          message: '删除成功'
        })
        this.getTableData()
      }
    },
	/** 清空按钮操作 */
	handleClean() {
		let v1 = this;
		this.$confirm('是否确认清空所有操作日志数据项?', '警告', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning'
		}).then(async () => {
		const res = await cleanSysOperationRecord();
		if (res.code === 0) {
			v1.$message({
			  type: 'success',
			  message: '删除成功'
			})
			v1.getTableData()
		  }else{
			  return v1.$message.error(res.msg);
		  }
		}).catch(function(){})
	},
	 /** 导出按钮操作 */
	handleExportSelected() {
		const ids = this.multipleSelection;
		this.$confirm('是否确认导出选中的所有操作日志数据项?', '警告', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning'
		}).then(async () => {
			this.downloadLoading = true;
			const res = await getSysOperationRecordsByIds({ids});
			if (res.code !== 0) return this.$message.error(res.msg);
			import('@/utils/Export2Excel').then(excel => {
				const tHeader = ['序号','操作人员', '时间', '描述', '状态码', '耗时', '主机', '操作地点', '浏览器', '操作系统', '平台', '请求方法', '请求路径', '参数', '响应'];
				const filterVal = ['ID','username', 'CreatedAt', 'desc', 'status', 'latency', 'ip', 'location', 'browser', 'os', 'platform', 'method', 'path', 'body', 'resp'];
				const data = formatJson(filterVal, res.data.records);
				excel.export_json_to_excel({
					header: tHeader,
					data,
					filename: '操作日志',
					autoWidth: true, // Optional
					bookType: 'xlsx' // Optional
				});
				this.downloadLoading = false
			});
			this.multipleSelection = []
			this.multiple = true;
		}).catch(function(){})
	},
	handleExportAll() {
		this.$confirm('是否确认导出选中的所有操作日志数据项?', '警告', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning'
		}).then(async () => {
			this.downloadLoading = true;
			var queryParams = JSON.parse(JSON.stringify(this.searchInfo));
			queryParams.page = -1;
			queryParams.pageSize = -1;
			const res = await getSysOperationRecordList(queryParams);
			if (res.code !== 0) return this.$message.error(res.msg);
			import('@/utils/Export2Excel').then(excel => {
				const tHeader = ['序号', '操作人员', '时间', '描述', '状态码', '耗时', '主机', '操作地点', '浏览器', '操作系统', '平台', '请求方法', '请求路径', '参数', '响应'];
				const filterVal = ['ID','username', 'CreatedAt', 'desc', 'status', 'latency', 'ip', 'location', 'browser', 'os', 'platform', 'method', 'path', 'body', 'resp'];
				const data = formatJson(filterVal, res.data.list);
				excel.export_json_to_excel({
					header: tHeader,
					data,
					filename: '操作日志',
					autoWidth: true, // Optional
					bookType: 'xlsx' // Optional
				});
				this.downloadLoading = false
			})
		}).catch( (err) => {})
	},
    fmtBody(value){
      try{
        return JSON.parse(value)
      }catch (err){
        return  value
      }
    },
	async getAllApiPathAndDesc(){
		const res = await getApiPathAndDesc();
		if (res.code !== 0){
			return this.$message.error(res.msg);
		}
		const api_list = res.data.apis;
		for (var i = 0; i < api_list.length; i++){
			this.api_path_list.push(api_list[i].path);
			this.api_desc_list.push(api_list[i].description);
		}
	}
  },
  created() {
    this.getTableData()
	this.getAllApiPathAndDesc();
  }
}
</script>

<style lang="scss">
.table-expand {
  padding-left: 60px;
  font-size: 0;
  label {
    width: 90px;
    color: #99a9bf;
    .el-form-item {
      margin-right: 0;
      margin-bottom: 0;
      width: 50%;
    }
  }
}
.popover-box {
  background: #112435;
  color: #f08047;
  height: 600px;
  width: 420px;
  overflow: auto;
}
.popover-box::-webkit-scrollbar {
  display: none; /* Chrome Safari */
}
</style>